package com.ruoyi.common.utils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;

/**
 * 阿里云邮件发送：采用SMTP方式；
 */
public class AliMailUtil {

    public static int sendMail(String mail_user, String mail_password, String nickname, String[] mail_to, String mail_replay, String subject, String content, String file_path, String host, String port) {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        // 发件人的账号，填写控制台配置的发信地址,比如xxx@xxx.com
        props.put("mail.user", mail_user);
        // 访问SMTP服务时需要提供的密码(在控制台选择发信地址进行设置)
        props.put("mail.password", mail_password);
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };

        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession) {
        };
        try {
            // 设置发件人邮件地址和名称。填写控制台配置的发信地址,比如xxx@xxx.com。和上面的mail.user保持一致。名称用户可以自定义填写。
            InternetAddress from = new InternetAddress(props.getProperty("mail.user"), nickname);
            message.setFrom(from);
            //可选。设置回信地址
            if (StringUtils.isNotEmpty(mail_replay)){
                Address[] a = new Address[1];
                a[0] = new InternetAddress(mail_replay);
                message.setReplyTo(a);
            }

            if (mail_to != null && mail_to.length != 0) {
                InternetAddress[] internetAddressTO = new InternetAddress[mail_to.length];
                for (int i = 0; i < mail_to.length; i++) {
                    internetAddressTO[i] = new InternetAddress(mail_to[i]);
                }
                message.setRecipients(Message.RecipientType.TO, internetAddressTO);
            }

            // 设置邮件标题
            message.setSubject(subject);
            // 设置邮件的内容体
            message.setContent(content, "text/html;charset=UTF-8");
            if (StringUtils.isNotBlank(file_path)) {
                File file = new File(file_path);
                if (file.exists()) {
                    // 创建多重消息
                    Multipart multipart = new MimeMultipart();

                    BodyPart messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setContent(content, "text/html;charset=UTF-8");
                    // 设置文本消息部分
                    multipart.addBodyPart(messageBodyPart);
                    // 附件部分
                    messageBodyPart = new MimeBodyPart();
                    //设置要发送附件的文件路径
                    FileDataSource source = new FileDataSource(file_path);
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    //处理附件名称中文（附带文件路径）乱码问题
                    messageBodyPart.setFileName(MimeUtility.encodeText(file_path.substring(file_path.lastIndexOf("/") + 1)));
                    messageBodyPart.addHeader("Content-Transfer-Encoding", "base64");
                    multipart.addBodyPart(messageBodyPart);
                    // 发送含有附件的完整消息
                    message.setContent(multipart);
                }
            }
            // 发送附件代码，结束
            // 发送邮件
            Transport.send(message);
        } catch (Exception e) {
            String err = e.getMessage();
            System.out.println(err);
            return 0;
        }
        return 1;
    }

    public static void main(String[] args) {
//        AliMailUtil.sendMail("liujuntao@mail.api.ytxiaohe.com", "ljt123XYZ1", "nickName", "liujuntao@126.com".split(","), "liujuntao@126.com", "subject", "<h3>content</h3>", "D:\\ffnew_VAT_INVOICE.pdf");

        AliMailUtil.sendMail("362008040@qq.com", "xzauphiphvmvbhch", "小Z", "2972144171@qq.com".split(","), "", "subject", "con哈哈<br><br>哈哈哈哈tent", null, "smtp.qq.com", "465");


    }
}
